package org.jsbd.boss.util;

import org.apache.commons.lang.StringUtils;

public class VersonCompareUtil {

    /**
     * 发送短信的sdk版本控制专用 比较版本号的大小,前者大则返回一个1,后者大返回一个-1,相等则返回0 target第一位必须是1
     *
     * @param target
     * @param standard
     * @return
     */
    public static int compareVersion(String target, String standard) {
        if (target == null && standard == null) {
            return 0;
        }
        if (target == null) {
            return -1;
        }
        if (standard == null) {
            return 1;
        }

        // 注意此处为正则匹配，不能用"."；
        String[] versionArray1 = target.split("\\.");
        String[] versionArray2 = standard.split("\\.");
        if (!(versionArray1[0].equals("1") || versionArray1[0].length() == 2)) {
            return -1;
        }
        int idx = 0;
        // 取最小长度值
        int minLength = Math.min(versionArray1.length, versionArray2.length);
        int diff = 0;
        // 先比较长度
        // 再比较字符
        while (idx < minLength && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {
            ++idx;
        }
        // 如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }

    public static int compareSimulatorVersion(String target, String standard) {
        if (target == null && standard == null) {
            return 0;
        }
        if (target == null) {
            return -1;
        }
        if (standard == null) {
            return 1;
        }

        String[] versionArray1 = target.split("\\.");
        String[] versionArray2 = standard.split("\\.");
        int idx = 0;
        int minLength = Math.min(versionArray1.length, versionArray2.length);
        int diff = 0;
        while (idx < minLength && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {
            ++idx;
        }

        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }


    public static void main(String[] args) {
        System.out.println(compareVersion("1.2.1", "1.3"));
        System.out.println(compareVersion("1.3", "1.3"));
        System.out.println(compareVersion("18.2.1", "19.3"));
        System.out.println(compareVersion("19.2.1", "19.1"));
        System.out.println(compareVersion("19.2.1", "1.9.21"));

        System.out.println(compareSimulatorVersion("1.2.1", "1.3"));
        System.out.println(compareSimulatorVersion("2.21.1.1", "2.21.1"));
        System.out.println(compareSimulatorVersion("2.21", "1.2.1"));

    }
}
